<template>
  <div class="warehouse-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">仓库管理</span>
          <div class="header-buttons">
            <el-button type="success" @click="handleStockIn">入库</el-button>
            <el-button type="warning" @click="handleStockOut">出库</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和过滤区域 -->
      <div class="search-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchName"
              placeholder="请输入商品名称搜索"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select v-model="filterType" placeholder="商品类型" clearable>
              <el-option
                v-for="type in goodsTypeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="filterStatus" placeholder="库存状态" clearable>
              <el-option
                v-for="status in stockStatusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="6" style="text-align: right;">
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 表格区域 -->
      <div class="table-container">
        <table class="warehouse-table">
          <thead>
            <tr>
              <th>货物编号</th>
              <th>货物名称</th>
              <th>货物类型</th>
              <th>库存数量</th>
              <th>货物价格</th>
              <th>库存状态</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in filteredGoods" :key="item.cargoId">
              <td>{{ item.cargoId }}</td>
              <td>{{ item.cargoName }}</td>
              <td>
                <el-tag>{{ getGoodsTypeText(item.ctId) }}</el-tag>
              </td>
              <td>{{ item.stockQuantity }}</td>
              <td>{{ item.cargoPrice.toFixed(2) }}</td>
              <td>
                <el-tag :type="getStockStatusType(getStockStatus(item.stockQuantity))">
                  {{ getStockStatusText(getStockStatus(item.stockQuantity)) }}
                </el-tag>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </el-card>

    <!-- 入库/出库对话框 -->
    <el-dialog
      v-model="stockDialogVisible"
      :title="stockType === 'in' ? '入库' : '出库'"
      width="40%"
    >
      <el-form
        ref="stockForm"
        :model="currentStock"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品" prop="goodsId">
          <el-select
            v-model="currentStock.goodsId"
            placeholder="选择商品"
            @change="handleGoodsSelect"
          >
            <el-option
              v-for="cargo in cargos"
              :key="cargo.cargoId"
              :label="cargo.cargoName"
              :value="cargo.cargoId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number
            v-model="currentStock.quantity"
            :min="1"
            :max="stockType === 'out' ? currentStock.maxQuantity : undefined"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleStockOperation">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 商品详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="商品详情"
      width="50%"
    >
      <div v-if="currentGoodsDetails">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="仓库编号">{{ currentGoodsDetails.warehouse.warehouseId }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ currentGoodsDetails.cargo.cargoName }}</el-descriptions-item>
          <el-descriptions-item label="商品类型">{{ getGoodsTypeText(currentGoodsDetails.cargo.ctId) }}</el-descriptions-item>
          <el-descriptions-item label="库存数量">{{ currentGoodsDetails.warehouse.inventory }}{{ currentGoodsDetails.warehouse.unit }}</el-descriptions-item>
          <el-descriptions-item label="单价">{{ currentGoodsDetails.cargo.cargoPrice.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="库存状态">
            <el-tag :type="getStockStatusType(getStockStatus(currentGoodsDetails.warehouse.inventory))">
              {{ getStockStatusText(getStockStatus(currentGoodsDetails.warehouse.inventory)) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="生产日期">{{ formatTimestamp(currentGoodsDetails.cargo.produceDate) }}</el-descriptions-item>
          <el-descriptions-item label="保质期">{{ currentGoodsDetails.cargo.sellBy }}</el-descriptions-item>
          <el-descriptions-item label="商品描述" :span="2">{{ currentGoodsDetails.cargo.cargoDescribe }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { cargoOrderApi, cargoApi } from '../api/console'

// 接口类型定义
interface Cargo {
  cargoId: number
  cargoName: string
  ctId: number
  cargoPrice: number
  produceDate: number
  sellBy: string
  cargoDescribe: string
  stockQuantity: number
  unit: string
}

interface Warehouse {
  warehouseId: number
  cargoId: number
  storeId: number
  inventory: number
  unit: string
}

interface WarehouseDTO {
  warehouse: Warehouse
  cargo: Cargo
}

interface StockRecord {
  recordId: number
  goodsId: number
  type: 'in' | 'out'
  quantity: number
  operator: string
  operateTime: number
  remark: string
}

interface GoodsWithRecords extends WarehouseDTO {
  records: StockRecord[]
}

// 状态定义
const loading = ref(false)
const goods = ref<Cargo[]>([])
const cargos = ref<Cargo[]>([])
const searchName = ref<string>('')
const filterType = ref<number | ''>('')
const filterStatus = ref<string>('')

const detailsDialogVisible = ref(false)
const currentGoodsDetails = ref<WarehouseDTO | null>(null)

const stockDialogVisible = ref(false)
const stockType = ref<'in' | 'out'>('in')
const currentStock = ref<{
  goodsId?: number
  quantity: number
  type: 'in' | 'out'
  maxQuantity?: number
}>({
  goodsId: undefined,
  quantity: 1,
  type: 'in'
})
const stockForm = ref<FormInstance>()

// 商品类型选项
const goodsTypeOptions = [
  { value: 1, label: '原材料' },
  { value: 2, label: '成品' },
  { value: 3, label: '包装材料' }
]

// 库存状态选项
const stockStatusOptions = [
  { value: 'NORMAL', label: '正常' },
  { value: 'LOW', label: '库存不足' },
  { value: 'OUT', label: '缺货' }
]

// 表单验证规则
const rules = ref<FormRules>({
  goodsId: [
    { required: true, message: '请选择商品', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' }
  ]
})

// 计算属性：过滤后的商品列表
const filteredGoods = computed(() => {
  return goods.value.filter(good => {
    const nameMatch = !searchName.value || 
      good.cargoName.toLowerCase().includes(searchName.value.toLowerCase())
    const typeMatch = filterType.value === '' || good.ctId === filterType.value
    const statusMatch = !filterStatus.value || getStockStatus(good.stockQuantity) === filterStatus.value
    return nameMatch && typeMatch && statusMatch
  })
})

// 获取商品列表
const fetchGoods = async () => {
  try {
    loading.value = true
    const result = await cargoApi.getAllCargo()
    if (result.code === 200 && result.data) {
      goods.value = result.data
      console.log('Loaded goods count:', goods.value.length, 'firstId:', goods.value[0]?.cargoId, 'lastId:', goods.value[goods.value.length-1]?.cargoId)
    } else {
      ElMessage.error(result.message || '获取商品列表失败')
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取所有货物
const fetchAllCargo = async () => {
  console.log('开始获取所有货物...')
  try {
    const result = await cargoApi.getAllCargo()
    console.log('获取货物结果:', result)
    if (result.code === 200 && result.data) {
      cargos.value = result.data
      console.log('货物列表已更新:', cargos.value)
    } else {
      ElMessage.error(result.message || '获取货物列表失败')
    }
  } catch (error) {
    console.error('获取货物失败:', error)
    ElMessage.error('获取货物列表失败')
  }
}

// 获取商品类型文本
const getGoodsTypeText = (type: number): string => {
  const typeMap: Record<number, string> = {
    1: '原材料',
    2: '成品',
    3: '包装材料'
  }
  return typeMap[type] || '其它类型'
}

// 获取库存状态类型
const getStockStatusType = (status: string): string => {
  const types: Record<string, string> = {
    'NORMAL': 'success',
    'LOW': 'warning',
    'OUT': 'danger'
  }
  return types[status] || 'info'
}

// 获取库存状态文本
const getStockStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    'NORMAL': '正常',
    'LOW': '库存不足',
    'OUT': '缺货'
  }
  return statusMap[status] || '未知状态'
}

// 获取库存状态
const getStockStatus = (inventory: number): string => {
  if (inventory <= 0) return 'OUT'
  if (inventory < 10) return 'LOW'
  return 'NORMAL'
}

// 格式化时间戳
const formatTimestamp = (timestamp: number | string | null): string => {
  if (!timestamp) return '-'
  const time = typeof timestamp === 'string' ? parseInt(timestamp, 10) : timestamp
  if (isNaN(time)) return '-'

  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 重置搜索条件
const resetSearch = () => {
  searchName.value = ''
  filterType.value = ''
  filterStatus.value = ''
}

// 处理入库
const handleStockIn = () => {
  stockType.value = 'in'
  currentStock.value = {
    goodsId: undefined,
    quantity: 1,
    type: 'in'
  }
  stockDialogVisible.value = true
}

// 处理出库
const handleStockOut = () => {
  stockType.value = 'out'
  currentStock.value = {
    goodsId: undefined,
    quantity: 1,
    type: 'out'
  }
  stockDialogVisible.value = true
}

// 处理商品选择
const handleGoodsSelect = (goodsId: number) => {
  if (stockType.value === 'out') {
    const selectedGoods = goods.value.find(g => g.cargoId === goodsId)
    if (selectedGoods) {
      currentStock.value.maxQuantity = selectedGoods.stockQuantity
    }
  }
}

// 处理查看详情
const handleViewDetails = (goods: WarehouseDTO) => {
  currentGoodsDetails.value = goods
  detailsDialogVisible.value = true
}

// 处理入库/出库
const handleStockOperation = async () => {
  if (!stockForm.value) return
  
  await stockForm.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const { goodsId, quantity, type } = currentStock.value
        if (!goodsId) {
          ElMessage.error('请选择商品')
          return
        }

        // 出库时检查库存
        if (type === 'out') {
          const selectedGoods = goods.value.find(g => g.cargoId === goodsId)
          if (!selectedGoods) {
            ElMessage.error('未找到商品库存信息')
            return
          }
          if (selectedGoods.stockQuantity < quantity) {
            ElMessage.error('库存不足')
            return
          }
        }

                  const result = type === 'in' 
          ? await cargoOrderApi.stockIn(goodsId, quantity)
          : await cargoOrderApi.stockOut(goodsId, quantity)

        if (result.code === 200) {
          ElMessage.success('操作成功')
          stockDialogVisible.value = false
          fetchGoods()
        } else {
          ElMessage.error(result.message || '操作失败')
        }
      } catch (error) {
        ElMessage.error('操作失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 页面加载时获取数据
onMounted(async () => {
  await Promise.all([fetchGoods(), fetchAllCargo()])
})
</script>

<style scoped>
.warehouse-management-container {
  margin-left: 200px;
  margin-top: 45px;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.search-area {
  margin-bottom: 20px;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.warehouse-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  min-width: 800px;
}

.warehouse-table th,
.warehouse-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
  color: #333;
  vertical-align: middle;
}

.warehouse-table th {
  background-color: #f2f2f2;
  font-weight: bold;
  color: #333;
}

.warehouse-table tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

.warehouse-table tbody tr:hover {
  background-color: #f5f5f5;
}

.actions-column {
  white-space: nowrap;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 120px;
  height: 60px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  width: 100%;
}

.action-buttons .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0;
}

:deep(.el-select) {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .warehouse-management-container {
    margin-left: 0;
    width: 100%;
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    gap: 16px;
  }

  .title {
    width: 100%;
    text-align: center;
  }

  .header-buttons {
    width: 100%;
    justify-content: center;
  }

  .search-area {
    .el-row {
      margin: 0 !important;
    }

    .el-col {
      padding: 0 !important;
      margin-bottom: 10px;
    }

    .el-form-item {
      margin: 0 !important;
      width: 100%;
    }
  }

  .el-button {
    width: 100%;
    justify-content: center;
  }
}
</style> 